import { defineStore } from 'pinia'
import { classificationList } from '../utils/trueType'
import _ from 'lodash'
export const useClassificationListStore = defineStore('classificationList', {
    state: () => ({
        classificationList: [
            {
                categoryId: null,
                category: '',
                categoryIsDeactivate: 0,
                children: []
            }
        ] as classificationList[],
        selectedIds: <string[]>([]),
        pageNum: 1,
        pageSize: 5,
        total: 0,
        loading: false
    }),
    actions: {
        changeLoading() {
            this.loading = !this.loading
            setTimeout(() => {
                this.loading = !this.loading
            }, 500);
        },
        addSelectedIds(id: string) {
            if (this.selectedIds.includes(id)) {
                this.selectedIds.splice(this.selectedIds.indexOf(id), 1)
            } else {
                this.selectedIds.push(id)
            }
        },
        getIsDeactivated(id) {
            return this.classificationList.find(item => item.categoryId === id)?.categoryIsDeactivate
        }
    },
    getters: {
        // 新增：判断选中项的状态一致性
        selectedStatus(): { allDisabled: boolean, isAllActive: boolean } {
            // 获取所有选中的子分类状态
            const statusList = this.selectedIds.flatMap(subId => {
                for (const parent of this.classificationList) {
                    const child = parent.children?.find(c => c.subcategoryId === subId)
                    if (child) return [child.subcategoryIsDeactivate]
                }
                return []
            })

            if (statusList.length === 0) return { allDisabled: true, isAllActive: false }

            return {
                allDisabled: _.uniq(statusList).length > 1, // 存在不同状态时禁用操作
                isAllActive: _.every(statusList, v => v === 1) // 全部启用
            }
        }
    },
}
)